package com.example.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.example.demo.annotation.PassToken;
import com.example.demo.annotation.UserLoginToken;
import com.example.demo.utils.MD5Util;
import com.example.demo.utils.RedisOperator;
import com.example.demo.po.User;
import com.example.demo.service.TokenService;
import com.example.demo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("api")
public class UserApi {
    @Autowired
    UserService userService;
    @Autowired
    TokenService tokenService;
    @Autowired
    RedisOperator redisOperator;

    //登录
    @PostMapping("/login")
    public Object login(@RequestBody User user) {
        JSONObject jsonObject = new JSONObject();
        User userForBase = userService.findByUsername(user);
        if (userForBase == null) {
            jsonObject.put("message", "登录失败,用户不存在");
            return jsonObject;
        } else {
            if (!userForBase.getPassword().equals(MD5Util.md5(user.getPassword()))) {
                jsonObject.put("message", "登录失败,密码错误");
                return jsonObject;
            } else {
                String token = tokenService.getToken(userForBase);
                redisOperator.set(token, token);
                jsonObject.put("token", token);
                jsonObject.put("user", userForBase);
                return jsonObject;
            }
        }
    }

    @UserLoginToken
    @GetMapping("/getMessage")
    public String getMessage(HttpServletRequest httpServletRequest) {
        String token = httpServletRequest.getHeader("token");// 从 http 请求头中取出 token
        String userId = JWT.decode(token).getAudience().get(0);
        String redisToken = redisOperator.get(token);
        if (StringUtils.isEmpty(redisToken)) {
            return "验证失败";
        } else if (token.equals(redisToken)) {
            log.info("token ->{}", token);
            return "你已通过验证:" + userId;
        } else {
            return "验证失败";
        }
    }

    @PostMapping("/logout")
    public String logout(HttpServletRequest httpServletRequest) {
        String token = httpServletRequest.getHeader("token");// 从 http 请求头中取出 token
        redisOperator.del(token);
        return "logout ok";
    }

    @GetMapping("/todo")
    @PassToken
//    @UserLoginToken
    public String todo() {

        return "不需要token";
    }

    @PostMapping("/register")
    public Object register(@RequestBody User user) {

        int row = userService.register(user);
        if (row > 0) {
            user.setPassword(null);
            return user;
        } else {
            return "注册失败";
        }

    }

}